package com.joinway.framework.support.utils;

import java.lang.annotation.Annotation;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import com.joinway.framework.bean.security.annotation.Login;
import com.joinway.framework.core.utils.AopHelper;


public final class InterceptorHelper {

	private final static Logger log = LoggerFactory.getLogger(InterceptorHelper.class);
	
    public static String getUserId(Login login, Object output) throws Exception {
    	Assert.hasText(login.id(), "id cannot be empty for " + Login.class.getCanonicalName());
    	Assert.notNull(output, "output cannot be null for method annotated with " + Login.class.getCanonicalName());

    	Assert.isTrue(PropertyUtils.isReadable(output, login.id())
    			, "output object must contain " + login.id() + " field");
    	
    	Object value = PropertyUtils.getProperty(output, login.id());
    	if(value == null){
    		Assert.notNull(value, "userId cannot be null in class " + output.getClass().getCanonicalName());
    	}

    	String userId = StringUtils.trimToNull(String.valueOf(value));

    	Assert.notNull(userId, "userId cannot be null in class " + output.getClass().getCanonicalName());

    	return userId;
    }
    
    @SuppressWarnings("unchecked")
    public static<T extends Annotation> T getParameterAnnotation(Annotation[] anns, Class<T> c) {
        T t = null;

        if (ArrayUtils.isNotEmpty(anns)) {
            for (Annotation ann : anns) {
                if (ann.annotationType() == c) {
                    t = (T) ann;
                    break;
                }
            }
        }

        return t;
    }

	public static String getInputValue(ProceedingJoinPoint point, HttpServletRequest request, String key, int index) {
		String value = "";
		
		do{
			value = (String)request.getParameter(key);
			if(StringUtils.isNotBlank(value)) break;
			
			Object form = AopHelper.getInputArg(point, index);
			if(form == null) break;
			
			if(!PropertyUtils.isReadable(form, key)) break;
			
			try {
				value = String.valueOf(PropertyUtils.getProperty(form, key));
			} catch (Exception e) {
				log.warn("get userId error from input {}", form.getClass().getCanonicalName());
			}
		}while(false);
		
		return value;
	}
	
    private InterceptorHelper(){}
}
